<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/1/31
 * Time: 13:58
 */

namespace Lib\Middleware;


use Cache;
use Closure;
use Lib\Utils\CacheUtils;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class ResponseCache extends BaseMiddleware
{
    public function handle($request, Closure $next)
    {
        $key = CacheUtils::key($request);
        if (!env('IS_CACHE')) {
            $response = $next($request);
            try {
                CacheUtils::put($key, $response);
            } catch (Exception $e) {
                return $response;
            }
            return $response;
        }
        if (!Cache::get($key)) {
            $response = $next($request);
            try {
                CacheUtils::put($key, $response);
            } catch (Exception $e) {
                return $response;
            }
        }
        return Cache::get($key);
    }
}